const httpclient = require('../../utils/httpclient.js')
const md5Util = require('../../utils/md5.js')
const util = require('../../utils/util.js')

var app = getApp()
Page({
  data:{
    statusType:["全部","待付款","待收货","已完成"],
    currentTpye:0,
    tabClass: ["", "", "", ""],
    currentPage: 1,
    orderList:[],
    hidden:false,
    isRefresh:false,
    page:{
      pagenum:1
    }
  },
  statusTap:function(e){
     var curType =  e.currentTarget.dataset.index;
     if (curType != this.data.currentTpye){
       this.setData({
         currentTpye: curType,
         currentPage: 1,
         orderList:[]
       });
       this.onShow();
     }
  },
  refresh: function (e) {
    console.log(e);
    console.log('开始刷新!');
    wx.stopPullDownRefresh();
    this.setData({
      isRefresh:true
    });
  },
  loadMore: function () {
    // 如果没有到最后一页才加载新的数据
    if (this.data.currentPage < this.data.page.pagenum) {
      this.setData({ currentPage: this.data.currentPage + 1 });
      this.getDataFromServer(this.data.currentPage);
    }
  },
  cancelOrderTap:function(e){
    var that = this;
    var orderId = e.currentTarget.dataset.id;
     wx.showModal({
      title: '确定要取消该订单吗？',
      content: '',
      success: function(res) {
        if (res.confirm) {
          httpclient.req(
            "/mall/update_order_state",
            {
              order_id: orderId,
              state:'0'
            },
            'post',
            function (res) {
              if(res.data.result){
                that.setData({
                  currentPage: 1,
                  orderList: []
                });
                that.onShow();
              }
            },
            function (result) {
              console.log(result)
            }
          );
        }
      }
    })
  },
  toPayTap:function(e){
    var orderId = e.currentTarget.dataset.id;
    var money = e.currentTarget.dataset.money;
    var prepay_id = e.currentTarget.dataset.prepay_id;

    var that = this;
    console.log(parseInt(money * 100));
    //appid
    let app_id = app.globalData.appId;
    //商户号
    let mch_id = app.globalData.mch_id;
    //时间戳
    let timestamp = (new Date()).valueOf() + '';
    //商户key
    let shop_key = app.globalData.shop_key;
    //随机字符串
    let nonceStr = util.makeRandom(10) + '';
    //签名类型
    let signType = 'MD5';
    //package
    let _package = "prepay_id=" + prepay_id;
    let content = 'appId=' + app_id + '&nonceStr=' + nonceStr + '&package=' + _package
      + '&signType=MD5&timeStamp=' + timestamp + '&key=' + shop_key;

    //调起微信支付
    wx.requestPayment({
      'timeStamp': timestamp,
      'nonceStr': nonceStr,
      'package': _package,
      'signType': 'MD5',
      'paySign': md5Util.md5(content),
      'success': function (res) {
        var pages = getCurrentPages();
        var prevPage = pages[pages.length - 2];  //上一个页面
        let dishesList = prevPage.data.dishesList;
        dishesList.forEach(function (dishes, index) {
          dishes.forEach((dishe, s_index) => {
            dishe.count = 0;
          });
        });
        //直接调用上一个页面的setData()方法，把数据存到上一个页面中去
        prevPage.setData({
          cart: {},
          cartTotal: 0,
          cartPrice: 0,
          dishesList: dishesList
        })

        // 跳转到餐厅首页
        wx.navigateBack({

        });
      },
      'fail': function (res) {
        console.log("接口调用失败的回调函数");
        that.setData({ payFalse: false });
      }
    });
  },
  onLoad:function(options){
    // 生命周期函数--监听页面加载
    var that = this;
    /** 
     * 获取系统信息 
     */
    wx.getSystemInfo({
      success: function (res) {
        var n = 750/res.windowWidth;
        that.setData({
          winWidth: res.windowWidth ,
          winHeight: res.windowHeight,
          scrollHeight: res.windowHeight - (89/n),
          upperThreshold: 80/n
        });
      }
    });
  },
  onShow:function(){
    // 获取订单列表
    var that = this;
    that.setData({
      orderList:[]
    });
    that.getDataFromServer(1);
  },
  //获取网络数据的方法
  getDataFromServer: function (currentPage) {
    wx.showNavigationBarLoading() //在标题栏中显示加载
    var that = this;
    this.setData({
      hidden: false,
      hasMore: true
    });
    var postData = {
      currentPage: currentPage,
      user_id: app.globalData.userInfo.id
    }
    if (that.data.currentTpye == 1) {
      postData.state = 1
    }
    if (that.data.currentTpye == 2) {
      postData.state = '2,3';
    }
    if (that.data.currentTpye == 3) {
      postData.state = '4,0'
    }

    httpclient.req(
      "/mall/find_user_orders",
      postData,
      'post',
      function (res) {
        var orderList = that.data.orderList.concat(res.data.orders);
        if (orderList.length == 0) {
          that.setData({ hiddenNoCoupon: false });
        } else {
          that.setData({ hiddenNoCoupon: true });
        }
        that.setData({
          orderList: orderList,
          hidden: true,
          page: res.data.page,
          hasMore: false
        })
        wx.hideNavigationBarLoading() //完成停止加载
      },
      function (result) {
        console.log(result)
      }
    );
  },
  releaseLoad: function (e) {
    console.log('开始释放');
    // 如果是刷新状态才有效
    if (this.data.isRefresh){
      // 取得当前的pageY
      var pageY = e.changedTouches[0].pageY;
      var diffeY = pageY - this.data.pageY;
      if (diffeY>60){
        var that = this;
        if (that.data.hidden) {
          that.setData({
            currentPage: 1,
            orderList: []
          });
          that.onShow();
        }
      }
      this.setData({
        isRefresh:false
      });
    }
  },
  scrollStart: function (e) {
    console.log('触摸开始');
    // 记录开始时候触摸时候移动的y轴距离
    this.setData({
      pageY: e.changedTouches[0].pageY
    });
  }
})